package app

import (
	"TaylorTest/model"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

type Exception struct {
	Message string
	Stack   string
}

//请求上下文
type Context struct {
	Request        *http.Request       //request
	ResponseWriter http.ResponseWriter //response
	StartTime      time.Time           //请求开始时间
	Exception      Exception           //异常
	IsEnd          bool                //判断请求是否结束
}

//结束请求，执行该方法后不会再处理之后的Filter和Handler
func (ctx *Context) End() {
	ctx.IsEnd = true
}

//判断是否Ajax请求
func (ctx *Context) IsAjax() bool {
	return ctx.Request.Header.Get("X-Requested-With") == "XMLHttpRequest"
}

//将要返回的数据处理为json对象返回到客户端，例如大部分Get的操作
func (ctx *Context) Json(data interface{}) {
	result := model.JsonResult{IsSuccess: true, Data: data}
	resultJson, _ := json.Marshal(result)
	fmt.Fprintf(ctx.ResponseWriter, string(resultJson))
}

//空操作执行该方法会自动处理数据返回到客户端，例如Add,Update,Delete操作
func (ctx *Context) Success() {
	result := model.JsonResult{IsSuccess: true}
	resultJson, _ := json.Marshal(result)
	fmt.Fprintf(ctx.ResponseWriter, string(resultJson))
}
